<script setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref } from 'vue';
import { customerAPI } from '../api';
import { useDataStore } from '../stores';

const store = useDataStore()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const searchKeyword = ref('')
const form = ref({
  name: '',
  phone: '',
  email: '',
  address: ''
})
const isEdit = ref(false)

const rules = ref({
  name: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})

const formRef = ref(null)

// 加载客户数据
const loadCustomers = async () => {
  await store.fetchCustomers(searchKeyword.value)
}

// 搜索处理函数
const handleSearch = () => {
  loadCustomers()
}

// 重置搜索
const handleReset = () => {
  searchKeyword.value = ''
  loadCustomers()
}

onMounted(() => {
  loadCustomers()
})

const handleAdd = () => {
  dialogTitle.value = '新增客户'
  isEdit.value = false
  form.value = {
    name: '',
    phone: '',
    email: '',
    address: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑客户'
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该客户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await customerAPI.delete(row.id)
      ElMessage.success('删除成功')
      loadCustomers()
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }).catch(() => {})
}

const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    if (isEdit.value) {
      await customerAPI.update(form.value.id, form.value)
      ElMessage.success('编辑成功')
    } else {
      await customerAPI.create(form.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    loadCustomers()
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error(isEdit.value ? '编辑失败' : '添加失败')
    }
    console.error(error)
  }
}
</script>

<template>
  <div class="customers-container">
    <div class="header">
      <h2>客户管理</h2>
      <div class="header-right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索客户姓名/电话/邮箱/地址"
          style="width: 300px; margin-right: 10px"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <span>搜索</span>
            </el-button>
          </template>
        </el-input>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" @click="handleAdd">新增客户</el-button>
      </div>
    </div>

    <el-table :data="store.customers" style="width: 100%" v-loading="store.loading">
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="name" label="姓名" width="150" />
      <el-table-column prop="phone" label="电话" width="150" />
      <el-table-column prop="email" label="邮箱" width="220" />
      <el-table-column prop="address" label="地址" min-width="250" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.customers-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style> 